<template>
    <div class="app-container">
        <el-card shadow="never" v-loading="loading">
            <el-row :gutter="5">
                <el-col :span="24" class="main-card-view">
                    <el-row>
                        <el-card shadow="never" class="top-search-view-card">
                            <el-row>
                                <el-form :inline="true" :model="searchForm" class="demo-form-inline search-view">
                                    <el-form-item label="角色名称">
                                        <el-input v-model="searchForm.roleName" placeholder="请输入角色名称"></el-input>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="handleSearch" class="search-button">查询</el-button>
                                        <!--                                        <el-button type="success" @click="handleReset" class="reset-button">重置</el-button>-->
                                        <el-button type="primary" @click="showCreateDialog"
                                            class="new-button">添加</el-button>
                                    </el-form-item>
                                </el-form>
                            </el-row>
                        </el-card>
                    </el-row>

                    <el-row>
                        <el-card shadow="never">
                            <el-table :data="tableData" :stripe="true" style="width: 100%">

                                <el-table-column prop="roleName" align="center" label="角色名称" />
                                <el-table-column prop="description" align="center" label="角色描述" />
                                <el-table-column align="center" label="操作" width="200">
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="controls(scope.row)">权限控制</el-button>
                                        <el-button type="text" class="table-edit-btn"
                                            @click="showEditDialog(scope.$index, scope.row)"></el-button><!--编辑-->
                                        <el-button type="text" class="table-delete-btn"
                                            @click="handleDelete(scope.$index, scope.row)"></el-button><!--删除-->
                                    </template>
                                </el-table-column>
                            </el-table>
                            <XPagination ref="pageInfo" :total="total" :get-data="getList" />
                        </el-card>
                    </el-row>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
            <el-form label-width="80px" ref="form" :model="form" :rules="formRules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input :autosize="{ minRows: 4, maxRows: 6 }" type="textarea" v-model="form.description" />
                </el-form-item>
            </el-form>
            <template slot="footer">
                <el-button type="primary" @click="handleSave">保存</el-button>
            </template>
        </el-dialog>

        <el-dialog title="权限控制" :visible.sync="treeDialog" width="60%">
            <el-tree ref="tree" :data="treeData" check-strictly show-checkbox node-key="uid"
                :default-checked-keys="checkedArr" :props="defaultProps" default-expand-all>
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="treeDialog = false" class="btn-cancel">取 消</el-button>
                <el-button type="primary" @click="treeHanld">确 定</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
import XPagination from "../../components/xpagination/XPagination";
import * as sysRole from "../../api/sysRole"
import * as columnInfo from "../../api/columnInfo"
import * as formUtils from "../../utils/formUtils";
export default {
    name: "list",
    components: { XPagination },
    data () {
        return {
            searchForm: {
                roleName: ""
            },
            tableData: [],
            treeData: [],
            loading: false,
            dialogVisible: false,
            treeDialog: false,
            total: 0,
            dialogTitle: "添加角色",
            form: {
                uid: "",
                roleName: "",
                description: "",
            },
            editStatus: "add",
            formRules: {
                roleName: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
                description: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
            },
            checkedArr: [],
            defaultProps: {
                children: 'children',
                label: 'columnName'
            },
            roleId: ''
        }
    },
    methods: {
        getList (pageInfo) {
            const param = {
                ...this.searchForm,
                ...pageInfo
            }
            // sysRole.queryByPage(param).then(response => {
            //     console.log(response)
            //     this.tableData = response.data.data.rows
            //     this.total = response.data.data.total
            //     this.loading = false
            // }).catch(error => {
            //     console.log(error)
            // })
        },
        handleDelete (index, data) {
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const param = {
                    uid: data.uid,
                }
                this.loading = true
                sysRole.deleteById(param).then(result => {
                    this.loading = false
                    this.$message.success(result.data.msg)
                    this.handleSearch()
                }).catch(error => {
                    this.loading = false
                    console.log(error)
                })
            }).catch(() => {
                console.log('取消删除')
            });
        },
        handleSearch () {
            this.$refs.pageInfo.loadData()
        },
        showCreateDialog () {
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.dialogTitle = "添加角色"
                this.editStatus = "add"
                this.$refs.form.resetFields()
                this.form = Object.assign({}, this.$options.data().form)
            })
        },
        handleSave () {
            if (this.editStatus === "add") {
                this.handleAdd()
            } else {
                this.handleEdit()
            }
        },
        handleAdd () {
            this.$refs["form"].validate((valid) => {
                if (!valid) {
                    return false
                }
                const param = Object.assign({}, this.form)
                formUtils.filterFormFields(param)
                sysRole.insert(param).then(result => {
                    this.$message.success(result.data.msg)
                    this.dialogVisible = false
                    this.handleSearch()
                }).catch(error => {
                    this.$message.error(error)
                    console.log(error)
                })

            })
        },
        handleEdit () {
            this.$refs["form"].validate((valid) => {
                if (!valid) {
                    return false
                }
                const param = Object.assign({}, this.form)
                formUtils.filterFormFields(param)
                sysRole.update(param).then(result => {
                    this.$message.success(result.data.msg)
                    this.dialogVisible = false
                    this.handleSearch()
                }).catch(error => {
                    this.$message.error(error)
                    console.log(error)
                })
            })
        },
        showEditDialog (index, data) {
            this.dialogVisible = true
            this.$nextTick(() => {
                this.$refs.form.resetFields()
                this.form = Object.assign({}, data)
                this.dialogTitle = "编辑角色"
                this.editStatus = "edit"
            })

        },
        getTree () {
            columnInfo.queryTree({}).then(response => {
                if (response.data.data) {
                    console.log(response)
                    this.treeData = response.data.data
                    this.treeData.sort((a, b) => a.sortNum - b.sortNum);
                    this.treeData.forEach(node => {
                        if (node.children.length > 0) {
                            node.children.sort((a, b) => a.sortNum - b.sortNum); // 递归对子节点进行排序
                        }
                    });
                }
            }).catch(error => {
                this.loading = false
                console.log(error)
            })
        },
        buildTree (data) {
            let hashTable = Object.create(null);
            data.forEach(aData => hashTable[aData.uid] = { ...aData, children: [] });
            let tree = [];
            data.forEach(aData => {
                if (aData.pid) hashTable[aData.pid].children.push(hashTable[aData.uid]);
                else tree.push(hashTable[aData.uid])
            });
            return tree.sort((a, b) => a.sort - b.sort);
        },
        controls (row) {
            this.treeDialog = true
            this.roleId = row.uid
            sysRole.queryRoleList({ roleId: row.uid }).then(response => {
                let arr = []
                if (response.data.data.rows) {
                    response.data.data.rows.forEach(item => {
                        arr.push(item.menuId)
                    })
                }
                this.$nextTick(() => {
                    this.$refs.tree.setCheckedKeys(arr);
                });
            }).catch(error => {
                console.log(error)
            })
        },
        treeHanld () {
            const param = {
                roleId: this.roleId,
                menuIds: this.$refs.tree.getCheckedKeys()
            }
            sysRole.batchInsert(param).then(response => {
                if (response.data) {
                    this.treeDialog = false
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                }
            }).catch(error => {
                console.log(error)
            })
        },
    },
    mounted () {
        this.handleSearch()
        this.getTree()
    }
}
</script>

<style scoped lang="scss"></style>
